package com.gitee.wsl.logger


import com.gitee.wsl.logger.disk.BaseLogDiskStrategy
import java.io.File
import java.io.PrintWriter
import java.io.StringWriter

class FileLogPrinter( val logDiskStrategy: BaseLogDiskStrategy) :
    LogPrinter {
    override fun log(level: LogLevel, tag: String, messageAny: Any?, throwable: Throwable?) {
        val logBody = messageAny.toString()
        val logFilePath = logDiskStrategy.internalGetLogPrintPath(System.currentTimeMillis(),level, logBody, logBody.length.toLong())
        if(logFilePath.isNullOrEmpty()){
            return
        }
        val logFile = File(logFilePath)
        val parentFile = logFile.parentFile
        try {
            //创建父文件夹
            if (parentFile != null) {
                if (!parentFile.exists() || !parentFile.isDirectory) {
                    val isSuccess = parentFile.mkdirs()
                    if (!isSuccess) {
                        debugLog("无法创建日志文件夹:" + parentFile.absolutePath)
                        return
                    }
                }
            }
            //创建文件
            if (!logFile.exists() || !logFile.isFile) {
                val isCreateSuccess = logFile.createNewFile()
                if (!isCreateSuccess ) {
                    debugLog("无法创建日志文件:" + logFilePath)
                    return
                }
            }
            logFile.appendText(logBody)
        } catch (e: Exception) {
            debugLog("日志写入异常，日志文件名称=" + logFilePath)
            debugLog(e.getStackTraceString())
        }
    }

}

fun LogPrinter.Companion.useFile(logDiskStrategy: BaseLogDiskStrategy) = FileLogPrinter(logDiskStrategy)

internal fun Throwable.getStackTraceString(): String {
    val sw = StringWriter(256)
    val pw = PrintWriter(sw, false)
    printStackTrace(pw)
    pw.flush()
    return sw.toString()
}